<template>
  <view>
    <!-- 1.头部搜索框 -->
    <MySearch />
    <!-- 2.tabs 选项卡 -->
    <u-tabs :list="tabsList" lineColor="#ea4350" :scrollable="false"></u-tabs>
    <!-- 3.商品列表 -->
    <view class="goods-list" v-for="item in goodsList" :key="item.goods_id">
      <navigator
        class="goods-item"
        :url="`/pages/goods_detail/goods_detail?goods_id=${item.goods_id}`"
      >
        <image
          :src="item.goods_small_logo || defaultImage"
          mode="scaleToFill"
          class="goods-image"
        />
        <view class="goods-info">
          <view class="goods-name">{{ item.goods_name }}</view>
          <view class="goods-price">{{ item.goods_price }}</view>
        </view>
      </navigator>
    </view>
  </view>
</template>

<script>
import { getGoodsSearchList } from "@/api/goods";
export default {
  data() {
    return {
      // 占位图片,微信小程序中，尽量不要用本地图片，尽量使用网络图片，因为小程序一个包大小限制为2048kb
      defaultImage:
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.doubanio.com%2Fview%2Fgroup_topic%2Fl%2Fpublic%2Fp443184895.jpg&refer=http%3A%2F%2Fimg9.doubanio.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1679036801&t=d85fb0154aff3deedbb7babe8c390bfc",
      queryParams: {},
      tabsList: [
        {
          name: "综合",
        },
        {
          name: "销量",
        },
        {
          name: "价格",
        },
      ],
      goodsList: [],
      // 商品总数
      total: 0,
    };
  },
  // onLoad 生命周期钩子可以获取页面参数
  onLoad(query) {
    // console.log("获取页面参数", query);
    this.queryParams = {
      // 关键字
      query: query.query,
      // 分类id
      cid: query.cid,
      // 页码
      pagenum: 1,
      // 页容量
      pagesize: 20,
    };
    this.getGoodsList();
  },
  // 上拉触底事件
  onReachBottom() {
    // 判断是否还要加载数据，
    if (this.total <= this.goodsList.length) {
      // 显示消息提示框
      return uni.showToast({
        title: "再划~就走光啦",
        icon: "none",
      });
    }
    // 页码累加
    this.queryParams.pagenum++;
    // 根据新的请求参数获取数据
    this.getGoodsList();
  },
  // 下拉刷新
  async onPullDownRefresh() {
    this.goodsList = [];
    this.queryParams.pagenum = 1;
    this.total = 0;
    await this.getGoodsList();
    uni.stopPullDownRefresh();
  },
  methods: {
    async getGoodsList() {
      /*  const [error, res] = await uni.request({
        url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/search",
        method: "GET",
        data: this.queryParams,
      });
      if (!error) {
        this.goodsList = res.data.message;
        console.log(this.goodsList);
      } else {
        console.log(error);
      } */
      //   对uni.request封装，封装到了src/utils/request.js中，让操作变简洁
      const res = await getGoodsSearchList(this.queryParams);
      console.log(res);
      // this.goodsList = res.data.message.goods;
      this.goodsList.push(...res.data.message.goods);
      this.total = res.data.message.total;
    },
  },
};
</script>

<style lang="scss"></style>
